package com.bank.common.commonUtil;

import com.bank.common.exceptionUtil.CustomedException;
import com.bank.common.resultUtil.ResultCodeEnum;
import com.bank.common.stringUtil.UUIDUtils;
import io.netty.util.Constant;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author Cejay1314
 * @version 1.0
 * @create 2023/4/2 21:57
 */
public class FileUtil {
    static String pathName = "D:/practise/projects/ElectronicBank/backend/files";

    public static String storeFile(MultipartFile file) throws IOException {
//        获取文件名称
        String fileName = file.getOriginalFilename().replace("_","" );
//        计算文件大小
        int size = (int) (file.getSize()/1024);
//        将文件名称分割为前缀，后缀两部分
//        attention: . means everythings. So we need to use \\. instead of .
        String[] fileNameSplit = fileName.split("\\.");
//        判断文件名称是否规范
        if(fileNameSplit.length > 2) throw new CustomedException(ResultCodeEnum.FILE_NAME_FORMAT_FAILED);
        //转换文件名称，统一为    “前缀+UUID+后缀“
        StringBuilder tarFileName = new StringBuilder();
        tarFileName.append(fileNameSplit[0]).append(UUIDUtils.getUUID()).append("." + fileNameSplit[1]);
//        生成路径
        String path = pathName + '/' + tarFileName;

//        生成文件
        java.io.File dest = new java.io.File(path);
        file.transferTo(dest);
        return tarFileName.toString();
    }

    public static void downFile(String name, HttpServletResponse response) {
        //设置文件路径
        File file = new File(pathName + '/' + name);
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.setCharacterEncoding("utf-8");
            response.addHeader("Content-Disposition", "attachment;fileName=" + name);// 设置文件名
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}
